package HomeService

import (
	"context"
	"database/sql"
	"fmt"
	"gdshop-font-api-go/app/entity"
	"gdshop-font-api-go/app/request/HomeReq"
	"gdshop-font-api-go/app/response/HomeResp"
	"gdshop-font-api-go/app/service/LogService"
	"gdshop-font-api-go/library/response"
	"gdshop-font-api-go/library/tools"
	toolsDb "gdshop-font-api-go/library/tools/db"
	toolsJwt "gdshop-font-api-go/library/tools/jwt"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/util/gconv"
	"github.com/gogf/gf/util/grand"
)

func Login(ctx context.Context, parames *HomeReq.Login) *response.JsonResponse {
	if parames.Type == "" || parames.Type == "password" {
		return doLogin(ctx, parames)
	}
	if parames.Type == "vcode" {
		return quickLogin(ctx, parames)
	}

	return response.FailByRequestMessage(nil, "不支持的类型")
}

// 普通登陆，账号密码
func doLogin(ctx context.Context, parames *HomeReq.Login) *response.JsonResponse {
	memberDb := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "member")
	memberModel := (*entity.Member)(nil)
	err := memberDb.Where(g.Map{
		"mobile": parames.Account,
	}).Struct(&memberModel)
	if err != nil {
		if err == sql.ErrNoRows {
			return response.FailByRequestMessage(nil, "请输入正确的账号密码")
		}
		return response.FailByRequestMessage(nil, err.Error())
	}
	if memberModel == nil {
		return response.FailByRequestMessage(nil, "账号未注册")
	}
	// 判断密码是否正确
	if tools.EncryptPassword(parames.Password, memberModel.PasswordSalt) != memberModel.Password {
		// 记录错误登陆日志，后面做封IP处理
		fmt.Println("登录hash ", tools.EncryptPassword(parames.Password, memberModel.PasswordSalt))
		return response.FailByRequestMessage(nil, "请输入正确的账号密码")
	}

	if memberModel.Status < 1 {
		return response.FailByRequestMessage(nil, "账号被禁用")
	}

	resp := new(HomeResp.Login)
	if err := gconv.Struct(memberModel, resp); err != nil {
		return response.FailByRequestMessage(nil, "数据转换失败")
	}

	tokenString, err := toolsJwt.GenerateLoginToken(memberModel.Id, memberModel.Realname)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	resp.Token = tokenString

	// 写登陆日志
	LogService.MemberLoginLog(memberModel)

	return response.SuccessByRequestMessageData(nil, "成功", resp)
}

// 快速登陆，账号和验证，如果账号不存在，自动注册
func quickLogin(ctx context.Context, parames *HomeReq.Login) *response.JsonResponse {
	if !tools.VerifyVCode(parames.Account, parames.Vcode) {
		return response.FailByRequestMessage(nil, "验证码错误")
	}

	memberDb := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "member")
	memberModel := (*entity.Member)(nil)
	err := memberDb.Where(g.Map{
		"mobile": parames.Account,
	}).Struct(&memberModel)
	if err != nil {
		if err == sql.ErrNoRows {
			// 找不到用户，使用快速注册
			pwd := grand.Letters(10)
			return QuickRegister(ctx, &HomeReq.Register{
				Mobile:    parames.Account,
				Password:  pwd,
				Password2: pwd,
			})
		}
		return response.FailByRequestMessage(nil, err.Error())
	}

	// 找到用户
	if memberModel.Status < 1 {
		return response.FailByRequestMessage(nil, "账号被禁用")
	}

	resp := new(HomeResp.Login)
	if err := gconv.Struct(memberModel, resp); err != nil {
		return response.FailByRequestMessage(nil, "数据转换失败")
	}

	tokenString, err := toolsJwt.GenerateLoginToken(memberModel.Id, memberModel.Realname)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	resp.Token = tokenString

	// 写登陆日志
	LogService.MemberLoginLog(memberModel)

	return response.SuccessByRequestMessageData(nil, "成功", resp)
}
